public class 逆波兰表达式求值 {

    /**
     * https://leetcode.cn/problems/evaluate-reverse-polish-notation/?envType=problem-list-v2&envId=array
     * 手写栈来实现逆波兰表达式
     */


    public static int MAXN = 10001;
    public static int[] nums = new int[MAXN];
    public int evalRPN(String[] tokens) {
        int top = 0;
        for(String token : tokens){
            if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
                //如果栈小于2个元素, 报错
                if(top < 2){
                    return Integer.MIN_VALUE;
                }
                //运算压入栈, 先出栈的是第二个元素
                int b = nums[--top];
                int a = nums[--top];
                if(token.equals("+")){
                    nums[top++] = a + b;
                }else if(token.equals("-")){
                    nums[top++] = a - b;
                }else if(token.equals("*")){
                    nums[top++] = a * b;
                }else if(token.equals("/")){
                    nums[top++] = a / b;
                }
            }else{
                nums[top++] = Integer.parseInt(token);
            }
        }
        return nums[0];
    }
}
